package cn.kone.user.controller;

import cn.kone.user.domain.User;
import cn.kone.user.domain.query.UserQuery;
import cn.kone.user.service.IUserService;
import cn.kone.base.utlis.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询全部")
    public R<List<User>> findAllUsers() {

        List<User> all = userService.findAll();
        return R.ok(all);
    }

    /**
     * 查询单个
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个")
    public R<User> findOneUsers(@PathVariable("id") Long id) {
        User one = userService.findOne(id);
        return R.ok(one);
    }

    /**
     * 新增和修改
     *
     * @param user
     * @return
     */
    @PutMapping
    @ApiOperation(value = "新增和修改")
    public R<Void> addOrUpdateUser(@RequestBody User user) {

        Long id = user.getId();
        try {
            if (id == null) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    /**
     * 删除单个
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个")
    public R<Void> deleteUsers(@PathVariable("id") Long id) {
        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    /**
     * 分页查询
     * @param userQuery
     * @return
     */
    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageInfo<User> pageQuery(@RequestBody UserQuery userQuery) {

        List<User> list = userService.pageQuery(userQuery);
        return new PageInfo<User>(list);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除")
    public R<Void> batchDeleteUser(@RequestBody Long[] ids){
        try {
            userService.batchDeleteUser(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

}
